<?php
session_start();
include '../conn.php'; // 确保这是正确的路径到你的数据库连接文件


// 检查是否设置了所有必要的参数
if (!isset($_REQUEST['uid']) || !isset($_REQUEST['gid'])) {
    echo "非法访问！";
    exit;
}
$uid = $_REQUEST['uid'];
print_r($uid);
$gid = $_REQUEST['gid'];
print_r($gid);
// 检查用户是否存在
$sql = "SELECT * FROM user WHERE id = " . $uid;
$result = $conn->query($sql);

// 判断是否已经添加进来了
$checkCollectSql = "SELECT * FROM collect WHERE user_id = " . $uid . " AND good_id = " . $gid;
// 执行的sql语句
echo "SQL: " . $checkCollectSql;
$resultCollect = $conn->query($checkCollectSql);
// print_r(1);
// print_r($resultCollect);
// $row2 = $resultCollect>fetch_assoc();
// print_r($row2);

if ($result && $result->num_rows > 0) {
    // 获取查询结果的第一行
    $row = $result->fetch_assoc();	
	// 打印结果
	print_r($row['uname']);
	
	if ($resultCollect && $resultCollect->num_rows > 0) {
		//  while ($row = $resultCollect->fetch_assoc()) {
		//     print_r($row);
		// }
		// header("Location: ../goods.php?id=$gid&uid=$uid");
		// 已经收藏了
		echo "<script>alert('已经收藏了！'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";

		echo "已经收藏了！";
		$conn->close();
		
	}else{
		// 添加收藏
		$sql2 = "INSERT INTO collect (good_id, user_id) VALUES (".$gid.", ".$uid.")";
		if ($conn->query($sql2)) {
			echo "<script>alert('收藏成功了！'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";
			

			echo "收藏成功！";
			$conn->close();
		  }else {
			echo "收藏失败";
			$conn->close();
		  }
	}
	
} else {
    echo "没有找到用户或查询失败";
}


?>